<template>
  <div>
    <p @click="activeSubtractOrAdd(0)">
      <span class="arrowLeft"></span>
    </p>
    <!-- 连续页码数的start 为2的时候再显示 -->
    <p @click="emit('getActive', 1)" v-if="gap.start >= 2">1</p>
    <p v-if="gap.start >= 3">...</p>
    <!--  循环连续页码数的最后一个 这样比 循环总共数字 少判断 -->
    <template v-for="(num, i) in gap.end" :key="i">
      <!-- 连续页码数有几个我们就渲染几个 所以比连续页码数开始小的不要 -->
      <p
        v-if="num >= gap.start"
        @click="emit('getActive', num)"
        :class="{ activeBG: num == active }"
      >
        {{ num }}
      </p>
    </template>
    <p v-if="gap.end <= all - 2">...</p>
    <!-- 连续页码数的总数减少2 的时候再显示 -->
    <p @click="emit('getActive', all)" v-if="gap.end <= all - 1">{{ all }}</p>
    <p @click="activeSubtractOrAdd(1)">
      <span class="arrowRight"></span>
    </p>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, toRefs } from "vue";
const emit = defineEmits<{ (event: "getActive", num: number | string): void }>();
const props = defineProps<{ all: number; active: number; continuous: number }>();
// 总共
// 当前
// 连续页码数
const { all, active, continuous } = toRefs(props);
const gap = computed(() => {
  let start = 0;
  let end = 0;
  //   总页数小于连续页码数
  if (all.value < continuous.value) {
    start = 1;
    end = all.value;
  } else {
    // 算出连续页码数的一半 前后间隔
    start = active.value - Math.trunc(continuous.value / 2);
    end = active.value + Math.trunc(continuous.value / 2);
    //   如果start小于等于0的情况下
    if (start < 1) {
      start = 1;
      end = continuous.value;
    }
    // 最后end 大于了总数的情况下
    if (end > all.value) {
      end = all.value;
      start = all.value - continuous.value + 1;
    }
  }
  return { start, end };
});
const activeSubtractOrAdd = (num: number) => {
  if (active.value > 1 && !num) {
    emit("getActive", "subtract");
  }
  if (active.value < all.value && num) emit("getActive", "add");
};
</script>

<style lang="less" scoped>
div {
  display: flex;
  align-items: center;
  width: fit-content;
  margin-left: 100%;
  transform: translateX(-100%);
  padding-bottom: 20px;
  p {
    width: 38px;
    height: 35px;
    font-size: 20px;
    text-align: center;
    line-height: 35px;
    background-color: #f4f4f5;
    margin: 0 5px;
    color: #606266;
    &:hover {
      cursor: pointer;
      color: #409eff;
    }
  }
  .arrowLeft {
    margin: 50% 50%;
    display: block;
    border: 1px solid black;
    width: 10px;
    height: 10px;
    border-width: 1px 0 0 1px;
    transform: rotate(-45deg) translateY(-20%);
  }
  .arrowRight {
    margin-top: 50%;
    display: block;
    border: 1px solid black;
    width: 10px;
    height: 10px;
    border-width: 1px 1px 0 0px;
    transform: rotate(45deg) translateY(-20%);
  }
  .activeBG {
    background-color: #409eff;
    color: #fff !important;
  }
}
</style>
